package org.example.HttpClient.impl;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public abstract class JAxiosAsyncRun extends JAxiosEventProcessing {
    @Override
    public void Run() {
        HttpEntityEnclosingRequestBase RequestBase = new MyHttpEntityEnclosingRequestBase();

        RequestBase.addHeader("User-Agent", "Java HTTP Client");

        if (!axiosConfig.getHeader().isEmpty()) {
            // 添加请求头
            axiosConfig.getHeader().forEach(RequestBase::addHeader);
        }

        if (!axiosConfig.getParameter().isEmpty()) {
            // 构建带参数的 URL
            try {
                URIBuilder uriBuilder = new URIBuilder(axiosConfig.getUrl());
                axiosConfig.getParameter().forEach(uriBuilder::addParameter);
                URI build = uriBuilder.build();
                RequestBase.setURI(build);
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }
        } else {
            RequestBase.setURI(URI.create(axiosConfig.getUrl()));
        }

        try {
            RequestBase.setEntity(new UrlEncodedFormEntity(axiosConfig.getData()));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }


        // 执行请求并获取响应
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            CloseableHttpResponse execute = httpClient.execute(RequestBase);

            if ( execute.getStatusLine().getStatusCode() == 200) {
                super.RunThenFunctional(execute);
            } else  {
                super.RunCatchFunctional(execute);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            super.RunFinallyFunctional();
        }
    }
    @Override
    public void AsyncRun() {
        try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
            executorService.submit(this::Run);
        }
    }

    private class MyHttpEntityEnclosingRequestBase extends HttpEntityEnclosingRequestBase {
        @Override
        public String getMethod() {
            return axiosConfig.getMethod();
        }
    }
}
